<template>
  <div class="sjplatformtree">
    <el-input v-model="filterText" placeholder="检索关键字..." />
    <el-tree
      ref="treeRef"
      class="filter-tree"
      :data="data"
      :props="defaultProps"
      default-expand-all
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
    >
      <template #default="{ node }">
        <el-tooltip
          v-if="isOverflowed(node)"
          class="item"
          effect="light"
          :content="node.label"
          placement="top"
        >
          <span class="tree-node-content" :data-id="node.id">{{
            node.label
          }}</span>
        </el-tooltip>
        <span v-else class="tree-node-content" :data-id="node.id">{{
          node.label
        }}</span>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { ElTree } from "element-plus";
import { useRoleTree } from "../../../hooks/SystemManager/Role/useRoleTree";

interface Tree {
  id: string;
  label: string;
}

const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
  label: "label",
};

watch(filterText, (val) => {
  if (treeRef.value) {
    // 确保 treeRef 已经初始化
    treeRef.value.filter(val);
  }
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 使用数据处理 Hook
const { data, roleStore, fetchData } = useRoleTree();
fetchData(); // 调用数据获取方法

const handleNodeClick = (node) => {
  roleStore.setSelectedRoleNode(node);
};

function isOverflowed(node) {
  return node.label.length > 13;
}
</script>